//接口
import { getShopSellerReq, getGoodsListReq, getShopRateReq } from "@/api/shop";

const state = {
  shopData: {},
  goodsData: [],
  rateList: [],
};
const mutations = {
  SET_SHOP(state, data) {
    state.shopData = data;
  },
  SET_GOODS(state, data) {
    state.goodsData = data;
  },
  SET_RATE(state, data) {
    state.rateList = data;
  },
};
const actions = {
  A_sop({ commit }) {
    return new Promise(async (resolve) => {
      //发请求
      let res = await getShopSellerReq();
      //解构赋值
      let { data } = res.data;

      commit("SET_SHOP", data);
    });
  },
  A_getgoods({ commit }) {
    return new Promise(async (resolve) => {
      //发送请求
      let res = await getGoodsListReq();
      //解构参数
      let { code, data } = res.data;
      //判断
      if (code === 0) {
        data.forEach((v) => {
          v.foods.forEach((i) => {
            i.account = 0;
          });
        });
        //数据赋值
        commit("SET_GOODS", data);
        resolve();
      }
    });
  },
  //评价
  A_getShopRate({ commit }) {
    return new Promise(async (resolve) => {
      let res = await getShopRateReq();
      let { errno, data } = res.data;
      if (errno === 0) {
        commit("SET_RATE", data);
        resolve();
      }
    });
  },
};
const getters = {
  navitem(state) {
    return state.goodsData.map((v) => v.name);
  },
  //筛选
  goodRateList(state) {
    return state.rateList.filter((v) => {
      return v.score > 3;
    });
  },
  badRateList(state) {
    return state.rateList.filter((v) => {
      return v.score <= 3;
    });
  },
  //筛选除account大于0的食物
  filterFoodsList(state) {
    let tem = [];
    state.goodsData.forEach((v) => {
      v.foods.forEach((food) => {
        if (food.account > 0) {
          tem.push(food);
        }
      });
    });
    return tem;
  },
  //储存购物车的数量
  filterTotalCount(state,getters){
    return getters.filterFoodsList.reduce((total,cur)=>{
       return total +cur.account
    },0)
  },
  //购物车价格
  filterTotalMoney(state,getters){
    return getters.filterFoodsList.reduce((total,cur)=>{
       return total +cur.account *cur.price
    },0)
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
